package com.mytomcat.servlet;

import com.util.log.Logger;

import java.net.Socket;

public class MyHttpServletResponse {
    private static com.util.log.Logger log = Logger.getLogger(MyHttpServletResponse.class);

    private Socket socket;

    public MyHttpServletResponse(Socket socket) {
        this.socket = socket;
    }

    /**
     * 返回json响应消息
     */
    public void returnJsonResponse(int httpStatus, String content) throws Exception {
        if(socket.isClosed())
            return;
        // http响应头 + 内容体
        String response = "HTTP/1.1 " + httpStatus + " OK\n" // 该句最关键 指定了http协议
                + "Content-Type: application/json; charset=utf8\n"
                + "\r\n"
                + content;

        log.trace("返回http请求结果：");
        log.trace(response);
        socket.getOutputStream().write(response.getBytes("utf-8"));
    }

    /**
     * 返回html响应消息
     */
    public void returnHtmlResponse(int httpStatus, String html) throws Exception {
        // http响应头 + 内容体
        String response = "HTTP/1.1 " + httpStatus + " OK\n" // 该句最关键 指定了http协议
                + "Content-Type: text/html; charset=utf8\n"
                + "\r\n"
                + html;

        log.trace("返回http请求结果：");
        log.trace(response);
        socket.getOutputStream().write(response.getBytes("utf-8"));
    }
}
